#include "contactitem.h"
#include <QPixmap>

ContactItem::ContactItem()
    :m_image(NULL),
    m_scaledImage(NULL)
{
    m_key = "";
    m_name = "";
    m_jid = "";
    m_fullJid = "";

    //std::vector<char> m_photo;
    m_status = "";
    m_vcard = false;
    m_online = false;

    m_presence = -1;

}
ContactItem::~ContactItem()
{
    delete m_image;
    delete m_scaledImage;
}

ContactItem::ContactItem(ContactItem const& val)
    :m_image(NULL),
    m_scaledImage(NULL)
{
    copy(val);
}

void ContactItem::copy(ContactItem const& val)
{
    setName(val.m_name);
    setJid(val.m_jid);
    setFullJid(val.m_fullJid);
    setStatus(val.m_status);
    setGroups(val.m_groups);
    setPresence(val.m_presence);
    setOnline(val.m_online);
    setVcard(val.m_vcard);
    m_photo = val.m_photo;
}

void ContactItem::update(const ContactItem& val)
{
    if (val.m_name.length())
    {
        setName(val.m_name);
    }
    if (val.m_jid.length())
    {
        setJid(val.m_jid);
    }
    if (val.m_fullJid.length())
    {
        setFullJid(val.m_fullJid);
    }
    if (val.m_status.length())
    {
        setStatus(val.m_status);
    }
    if (val.m_groups.size())
    {
        setGroups(val.m_groups);
    }
    if (val.m_presence != -1)
    {
        setPresence(val.m_presence);
    }
    if (val.m_online)
    {
        setOnline(val.m_online);
    }
    if (val.m_vcard)
    {
        setVcard(val.m_vcard);
    }
    if (val.m_photo.size())
    {
        m_photo = val.m_photo;
    }
}

ContactItem& ContactItem::operator= (ContactItem const& val)
{
    copy(val);
    return *this;
}

const bool ContactItem::operator== (ContactItem const& val)
{
    return m_jid == val.m_jid;
}

void ContactItem::setPhoto(const char* bytes, int size){
    m_photo.resize(size);
    memcpy(&m_photo[0], bytes, size);
}

const QPixmap& ContactItem::image()
{
    if (!m_image)
    {
        m_image = new QPixmap;
    }
    if (m_image->isNull())
    {
        if (m_photo.size())
        {
            m_image->loadFromData((const uchar*)&m_photo.front(), m_photo.size());
        }
    }
    return *m_image;
}

const QPixmap& ContactItem::scaledImage()
{
    if (!m_scaledImage)
    {
        m_scaledImage = new QPixmap;
    }

    if (m_scaledImage->isNull())
    {
        if (!image().isNull())
        {
            *m_scaledImage = image().scaled(36,36, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        }
    }
    return *m_scaledImage;
}
